<?php
/*
+--------------------------------------------------------------------------
|   IKPHP [#RELEASE_VERSION#]
|   ========================================
|   By IKPHP Software
|   © 2013 - 2050 WeCenter. All Rights Reserved
|   http://www.ikphp.com
|   ========================================
|   Author: 小麦 <ikphp@sina.cn>
+---------------------------------------------------------------------------
*/
defined ( 'IN_IKPHP' ) or exit ( 'WebSite Access Denied' );
class application 
{
    /**
     * 应用程序初始化
     * @access public
     * @return void
     */
    static public function init() {
        // 加载动态应用公共文件和配置
        load_ext_file(CONF_PATH);
        // 定义当前请求的系统常量
        define('NOW_TIME',      $_SERVER['REQUEST_TIME']);
        define('REQUEST_METHOD',$_SERVER['REQUEST_METHOD']);
        define('IS_GET',        REQUEST_METHOD =='GET' ? true : false);
        define('IS_POST',       REQUEST_METHOD =='POST' ? true : false);
        define('IS_PUT',        REQUEST_METHOD =='PUT' ? true : false);
        define('IS_DELETE',     REQUEST_METHOD =='DELETE' ? true : false);
        define('IS_AJAX',       ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') || !empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')])) ? true : false);

       
        // URL调度
        dispatcher::dispatch();
            
        if(C('REQUEST_VARS_FILTER')){ 
			// 全局安全过滤
			array_walk_recursive($_GET,		'ik_filter');
			array_walk_recursive($_POST,	'ik_filter');
			array_walk_recursive($_REQUEST,	'ik_filter'); 
		}
        // URL调度结束标签
        hook::listen('url_dispatch');  
              
        // 日志目录转换为绝对路径
        C('LOG_PATH',   LOG_PATH.MODULE_NAME.'/');
        return ;
    }	
    /**
     * 运行应用实例 入口文件使用的快捷方法
     * @access public
     * @return void
     */
    static public function run() {
        // 应用初始化标签    
        hook::listen('app_init');	
        self::init();  
        // 应用开始标签  	
        hook::listen('app_begin'); 
        // Session初始化
        if(!IS_CLI){ 
            session(C('SESSION_OPTIONS'));
        }
        // 记录应用初始化时间
        G('initTime');
        self::exec();
        // 应用结束标签
        hook::listen('app_end'); 
        return ;
    }
    /**
     * 执行应用程序
     * @access public
     * @return void
     */
    static public function exec() { 
        if(!preg_match('/^[A-Za-z](\/|\w)*$/',CONTROLLER_NAME)){ // 安全检测
            $module  =  false;
        }else{
        	//创建控制器实例
            $module  =  controller(CONTROLLER_NAME,CONTROLLER_PATH); 
        }

        if(!$module) {
        	E(L('_CONTROLLER_NOT_EXIST_').':'.CONTROLLER_NAME); exit();
        } 

        // 获取当前操作名 支持动态路由
        if(!isset($action)){
            $action    =   ACTION_NAME.C('ACTION_SUFFIX');  
        }  
        
        try {
            if(!preg_match('/^[A-Za-z](\w)*$/',$action)){
                // 非法操作
                throw new Exception('System not allow this actioin: '.$action);
            }
            //执行当前操作
            $method =   new ReflectionMethod($module, $action);
            if($method->isPublic() && !$method->isStatic()) {
            	$class  =   new ReflectionClass($module);
                // 前置操作
                if($class->hasMethod('_before_'.$action)) {
                    $before =   $class->getMethod('_before_'.$action);
                    if($before->isPublic()) {
                        $before->invoke($module);
                    }
                }  
                // URL参数绑定检测
                if($method->getNumberOfParameters()>0 && C('URL_PARAMS_BIND')){
                    switch($_SERVER['REQUEST_METHOD']) {
                        case 'POST':
                            $vars    =  array_merge($_GET,$_POST);
                            break;
                        case 'PUT':
                            parse_str(file_get_contents('php://input'), $vars);
                            break;
                        default:
                            $vars  =  $_GET;
                    }
                    $params =  $method->getParameters();
                    $paramsBindType     =   C('URL_PARAMS_BIND_TYPE');
                    foreach ($params as $param){
                        $name = $param->getName();
                        if( 1 == $paramsBindType && !empty($vars) ){
                            $args[] =   array_shift($vars);
                        }elseif( 0 == $paramsBindType && isset($vars[$name])){
                            $args[] =   $vars[$name];
                        }elseif($param->isDefaultValueAvailable()){
                            $args[] =   $param->getDefaultValue();
                        }else{
                            E(L('_PARAM_ERROR_').':'.$name);
                        }   
                    }
                    // 开启绑定参数过滤机制
                    if(C('URL_PARAMS_SAFE')){
                        array_walk_recursive($args,'filter_exp');
                        $filters     =   C('URL_PARAMS_FILTER')?:C('DEFAULT_FILTER');
                        if($filters) {
                            $filters    =   explode(',',$filters);
                            foreach($filters as $filter){
                                $args   =   array_map_recursive($filter,$args); // 参数过滤
                            }
                        }                        
                    }
                    array_walk_recursive($args,'ik_filter');//安全过滤
                    $method->invokeArgs($module,$args);
                }else{
                	$method->invoke($module);
                }
                // 后置操作
                if($class->hasMethod('_after_'.$action)) {
                    $after =   $class->getMethod('_after_'.$action);
                    if($after->isPublic()) {
                        $after->invoke($module);
                    }
                }                
            	
            }else{
                // 操作方法不是Public 抛出异常
                throw new Exception('Method is not public: '.$action);
            }         
           
            
        } catch (Exception $exc) {
        	exceptions::exception_error($exc);
        }      
        
        return ;
    } 
    static public function logo(){
        return 'iVBORw0KGgoAAAANSUhEUgAAAFoAAAAeCAYAAACsYQl4AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAALJSURBVHja7FoxjptAFH1ruaGyb2AXqbGlrcnSU6xvsK5HQnFOsPgGREikDD7Begt6IupILLULfAO7onSKfCKWnfGCGbQknidZ8jDjP38eb/78P/LN6XSCQvcYKAoU0YpoBUV0bzEEgNn3zxGvM2WxWW7rvjEH4HKGJimLVzwbum+4AObUdFIWv5orD+0lgGVNfyMAGYCtZnkH3oBP/i/uWnbs1qyME80b7NhtUPGxvIZzOABIACSa5W3fEA3gruZCxw3GQvcNB8AXam6qJBOmDWwW437kob3WLM85M+Y9iObl+ThvYPeeXs4ewKogvLPQofuGCeCRmi8AVg1N/ASwps+e0/+Yh3bwwRFhQ/59A3Cs9E0APOWhveiMaN03pgCKrXMEsExZfGhoJtIszyHVzgVkP+ShbX4g0QH5uAKwEI3pUtFbACP6vkxZnLQxRvHYFXQv+nDYaZYX0S6sYpSHtjnoQM0ugBk11ymLt5JMi17WHP1BJPJxIJnkZenwe05Z7KjE7k8SMZBIcjX1k6208ZmUqi+YinbjUCIJQSk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